#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include "ringqueue.hpp"
#include "task.hpp"
using namespace std;

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
struct ThreadData
{
    ringqueue<task> *rq;
    string threadname;
};
void *consumer(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    ringqueue<task> *rq = td->rq;
    string name = td->threadname;
    while (true)
    {
        task t;
        rq->Pop(&t);
        t();
        pthread_mutex_lock(&lock);
        cout << "consumer a task,task is:" << t.show() << " who:" << name << " result:" << t.Getresult() << endl;
        pthread_mutex_unlock(&lock);
    }
    return nullptr;
}
void *productor(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    ringqueue<task> *rq = td->rq;
    string name = td->threadname;
    // sleep(3);
    // ringqueue<int> *rq = static_cast<ringqueue<int> *>(args);
    int len = opers.size();
    while (true)
    {
        int data1 = rand() % 10 + 1;
        usleep(10);
        int data2 = rand() % 10;
        char op = opers[rand() % len];
        task t(data1, data2, op);
        rq->Push(t);
        pthread_mutex_lock(&lock);

        cout << "productor create a task,task is:" << t.show() << " who: " << name << endl;
        pthread_mutex_unlock(&lock);

        sleep(1);
    }
    return nullptr;
}
int main()
{
    srand(time(nullptr) ^ getpid());
    ringqueue<task> *rq = new ringqueue<task>();
    pthread_t c[3], p[5];
    for (int i = 0; i < 3; i++)
    {
        ThreadData *td = new ThreadData();
        td->rq = rq;
        td->threadname = "consumer-" + to_string(i);
        pthread_create(c + i, nullptr, consumer, td);
    }
    for (int i = 0; i < 5; i++)
    {
        ThreadData *td = new ThreadData();
        td->rq = rq;
        td->threadname = "productor-" + to_string(i);
        pthread_create(p + i, nullptr, productor, td);
    }
    for (int i = 0; i < 3; i++)
    {
        pthread_join(c[i], nullptr);
    }
    for (int i = 0; i < 5; i++)
    {
        pthread_join(p[i], nullptr);
    }
    return 0;
}